<?php

/**
 * Created by PhpStorm.
 * User: CCA
 * Date: 2019/10/12
 * Time: 15:44
 */

namespace app\api\controller;


use app\api\BaseController;
use app\common\logic\ApiPayment;
use app\common\logic\Buy;
use app\common\model\Goodscommon;
use app\common\model\Goods;
use app\common\model\Member;
use app\common\model\Payment;
use app\common\model\Refundreturn;
use app\common\model\Seller;
use app\common\model\Huichao;
use app\common\model\Rsa;
use app\service\GoodsService;

use houdunwang\crypt\Crypt;
use Qiniu\Auth as Auth;
use think\Lang;

/**
 * @title 订单
 */
class Order extends BaseController
{
    private static $accountNumber = '50326'; #属性

   

    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        Lang::load(APP_PATH . 'home/lang/' . config('default_lang') . '/buy.lang.php');
        Lang::load(APP_PATH . 'home/lang/' . config('default_lang') . '/memberrefund.lang.php');
        Lang::load(APP_PATH . 'home/lang/' . config('default_lang') . '/memberorder.lang.php');
    }


    /**
     * @title 预订单
     * @description
     * @param string ifcart 是否来自购物车1是0否
     * @param string cart_id 商品信息格式id|number
     * @return {"code":200,"msg":"succeess"}
     * @author fuzz
     * @url /Order/prepare
     * @method POST
     *
     * @code 200 成功
     * @code 201 失败
     *
     */
    public function prepare()
    {
        if (empty(input('post.'))) {
            return json_fail_return(lang('wrong_argument'));
        }
        //商品购买分流
        $ifcart = input('post.ifcart'); #是否来自购物车1是0否
        $is_install = input('post.is_install', ''); #是否含有安装费 1：含有 0：不含  用于立即购买
        $address_id = input('post.address_id', '0'); #地址id 计算安装费
        $buy_logic = new Buy();
        $result = $buy_logic->buyStep1(input('post.cart_id/a'), $ifcart, $this->user_id, '', '', $is_install,$address_id);
       // p($result);die;
        if ($result['code'] != 'SUCCESS') {
            return json_fail_return($result['msg']);
        } else {
            $result = $result['data'];
            $freight_list = array();
            $goods_models = new Goods();
            foreach ($result['store_cart_list'] as $key => $goods) {
                //$freight_list[$key] = array();
                foreach ($goods as $ke => $good) {
                    $common = $goods_models->getWayBillIdByGoodsId($good['goods_id']);
                    $waybill_info = $goods_models->getIsBaoByGoodsId($common['waybill_id']);
                    $tmp = array(
                        'goods_id' => $good['goods_id'],
                        'store_id' => $good['store_id'],
                        'goods_commonid' => $good['goods_commonid'],
                        'weight' => $common['weight'],
                        'waybill_id' => $common['waybill_id'],
                        'is_w_v' => $common['is_w_v'],
                        'volume' => $common['volume'],
                        'goods_num' => $good['goods_num'],
                    );
                    $result['store_cart_list'][$key][$ke]['is_bao'] = $waybill_info['is_bao'];
                    $result['store_cart_list'][$key][$ke]['is_to_pay'] = $common['is_to_pay'];
                    $freight_list[] = $tmp;
                    if ($ifcart == 0) {
                        if (isset($is_install) && $is_install != '') {
                            if ($is_install == 1) {
                                $result['store_cart_list'][$key][$ke]['spec_values'] = '含有安装费;' . $result['store_cart_list'][$key][$ke]['spec_values'];
                            } elseif ($is_install == 0) {
                                $result['store_cart_list'][$key][$ke]['spec_values'] = '不含安装费;' . $result['store_cart_list'][$key][$ke]['spec_values'];
                            }
                        }
                    }
                }
            }
            $encrypted = crypt_en(json_encode($freight_list));
            $result['freight_list_hash'] = $encrypted;

            //p($result);die;
            json_success_return('success', $result);
        }
    }


    /**
     * @title 运费计算
     * @description
     * @param string freight_hash 订单hash码
     * @param string city_id 城市id
     * @param string area_id 区域id
     * @return {"code":200,"msg":"succeess"}
     * @author fuzz
     * @url /Order/freight
     * @method POST
     *
     * @code 200 成功
     * @code 201 失败
     *
     */
    public function freight($hash, $area_id)
    {
        /*$type_array = array(
            '6'=>array(
                    '0'=>array('goods_id'=>'111','is_home'=>1,'is_to_pay'=>0,'count'=>1),
                    '1'=>array('goods_id'=>'111','is_home'=>1,'is_to_pay'=>0,'count'=>1)
            ),
                '7'=>array(
                        '0'=>array('goods_id'=>'111','is_home'=>1,'is_to_pay'=>0,'count'=>1),
                        '1'=>array('goods_id'=>'111','is_home'=>1,'is_to_pay'=>0,'count'=>1)
            )
        );
        $type_array  = json_encode($type_array);
        echo $type_array;die;*/

        $type_array = input('post.type_array');
        /*{"6":[{"goods_id":"111","is_home":1,"is_to_pay":0,"count":1},{"goods_id":"111","is_home":1,"is_to_pay":0,"count":1}],"7":[{"goods_id":"111","is_home":1,"is_to_pay":0,"count":1},{"goods_id":"111","is_home":1,"is_to_pay":0,"count":1}]}*/

        $type_array = json_decode(htmlspecialchars_decode($type_array), true);
        $json_ = crypt_de($hash);
        $goods_waybill = json_to_array($json_);
        if (!$json_ || !$goods_waybill) {
            return json_fail_return('验证失败');
        }
        $freight_list = GoodsService::getInstance()->calculateFreight($goods_waybill, $area_id, $type_array);
        json_success_return($freight_list);
    }



    /**
     * @title 地区满减信息
     * @description
     * @param string freight_hash 订单hash码
     * @param string city_id 城市id
     * @param string area_id 区域id
     * @return {"code":200,"msg":"succeess"}
     * @author fuzz
     * @url /Order/changeAddr
     * @method POST
     *
     * @code 200 成功
     * @code 201 失败
     *
     */
    public function changeAddr()
    {
        $buy_logic = new Buy();

        $data = $buy_logic->changeAddr(input('post.freight_hash'), input('post.city_id'), input('post.area_id'), $this->user_id);
        if (!empty($data)) {
            json_success_return('success', $data);
        } else {
            exit();
        }
    }


    /**
     * @title 订单创建 34115.37 34000  76
     * @description
     * @param array cart_id 是否来自购物车1是0否
     * @param string pay_message 备注店铺id为键message为值
     * @param string order_from 固定值2
     * @param string ifcart 是否来自购物车
     * @param string pay_name 固定值online
     * @param string pay_name 是否保存增值税发票判断标志
     * @param string address_id 地址id
     * @param string buy_city_id 收货城市id
     * @param string allow_offpay 是否支持货到付款
     * @param string allow_offpay_batch 地区满减信息
     * @param string offpay_hash 地区满减信息
     * @param string offpay_hash_batch 地区满减信息
     * @return {"code":200,"msg":"succeess"}
     * @author fuzz
     * @url /Order/create
     * @method POST 
     * {"6":[{"goods_id":191,"count":2,"is_home":0,"is_to_pay":0}],"66":[{"goods_id":648,"count":2,"is_home":0,"is_to_pay":0}]}"
      * {"6":[{"goods_id":191,"count":2,"is_home":0,"is_to_pay":0}],"66":[{"goods_id":648,"count":2,"is_home":0,"is_to_pay":0}]}"
     * 
     * @code 200 成功
     * @code 201 失败
     *
     */
    public function create(Seller $seller)
    {
        $buy_logic = new Buy();
        $result = $buy_logic->buyStep2(input('post.'), $this->user_id, $this->user_info['member_name'], $this->user_info['member_email']);
         //p($result);die;
        if (!$result['code']) {
            return json_fail_return($result['msg']);
        }
        json_success_return('创建订单成功', $result['data']);
    }

    /**
     * @title 服务单订单创建
     * @description
     * @param array cart_id 是否来自购物车1是0否
     * @param string pay_message 备注店铺id为键message为值
     * @param string order_from 固定值2
     * @param string ifcart 是否来自购物车
     * @param string pay_name 固定值online
     * @param string pay_name 是否保存增值税发票判断标志
     * @param string address_id 地址id
     * @param string buy_city_id 收货城市id
     * @param string allow_offpay 是否支持货到付款
     * @param string allow_offpay_batch 地区满减信息
     * @param string offpay_hash 地区满减信息
     * @param string offpay_hash_batch 地区满减信息
     * @return {"code":200,"msg":"succeess"}
     * @author fuzz
     * @url /Order/create
     * @method POST
     *
     * @code 200 成功
     * @code 201 失败
     *
     */
    public function service_create()
    {
        $buy_logic = new Buy();
        $result = $buy_logic->serviceCreate(input('post.'), $this->user_id, $this->user_info['member_name'], $this->user_info['member_email']);
        //p($result);die;
        if (!$result['code']) {
            return json_fail_return($result['msg']);
        }

        json_success_return('创建订单成功', $result['data']);
    }

    /**
     * @title 拉取支付
     * @description
     * @param string pay_sn 支付流水号
     * @return {"code":200,"msg":"succeess"}
     * @author fuzz
     * @url /Order/payInfo
     * @method POST
     *
     * @code 200 成功
     * @code 201 失败
     *
     */
    public function payInfo()
    {
        $pay_sn = input('param.pay_sn');
        if (!preg_match('/^\d{20}$/', $pay_sn)) {
            return json_fail_return(lang('cart_order_pay_not_exists'));
        }

        $result = array();
        //查询支付单信息
        $order_model = new \app\common\model\Order();
        $pay_info = $order_model->getOrderpayInfo(array('pay_sn' => $pay_sn, 'buyer_id' => $this->user_id));
        if (empty($pay_info)) {
            return json_fail_return(lang('cart_order_pay_not_exists'));
        }
        $result['pay_info'] = $pay_info;

        //取子订单列表
        $condition = array();
        $condition['pay_sn'] = $pay_sn;
        $condition['order_state'] = array('in', array_values(array(ORDER_STATE_NEW, ORDER_STATE_PAY)));
        $order_list = $order_model->getOrderList($condition, '', 'order_id,order_state,payment_code,order_amount,rcb_amount,pd_amount,order_sn', '', '', array(), true);
        if (empty($order_list)) {
            return json_fail_return(lang('no_order_paid_was_found'));
        }

        //重新计算在线支付金额
        $pay_amount_online = 0;
        $pay_amount_offline = 0;
        //订单总支付金额(不包含货到付款)
        $pay_amount = 0;

        foreach ($order_list as $key => $order_info) {

            $payed_amount = floatval($order_info['rcb_amount']) + floatval($order_info['pd_amount']);
            //计算相关支付金额
            if ($order_info['payment_code'] != 'offline') {
                if ($order_info['order_state'] == ORDER_STATE_NEW) {
                    $pay_amount_online += ds_price_format(floatval($order_info['order_amount']) - $payed_amount);
                }
                $pay_amount += floatval($order_info['order_amount']);
            } else {
                $pay_amount_offline += floatval($order_info['order_amount']);
            }

            //显示支付方式与支付结果
            if ($order_info['payment_code'] == 'offline') {
                $order_list[$key]['payment_state'] = lang('cart_step2_arrival_pay');
            } else {
                $order_list[$key]['payment_state'] = lang('cart_step2_online_pay');
                if ($payed_amount > 0) {
                    $payed_tips = '';
                    if (floatval($order_info['rcb_amount']) > 0) {
                        $payed_tips = lang('card_has_been_paid') . '：￥' . $order_info['rcb_amount'];
                    }
                    if (floatval($order_info['pd_amount']) > 0) {
                        $payed_tips .= lang('prepaid_deposits_beenpaid') . '：￥' . $order_info['pd_amount'];
                    }
                    $order_list[$key]['order_amount'] .= " ( {$payed_tips} )";
                }
            }
        }
        $result['order_list'] = $order_list;

        //如果线上线下支付金额都为0，转到支付成功页
        if (empty($pay_amount_online) && empty($pay_amount_offline)) {
            $this->redirect('Buy/pay_ok', ['pay_sn' => $pay_sn, 'pay_amount' => ds_price_format($pay_amount)]);
        }

        //输出订单描述
        if (empty($pay_amount_online)) {
            $order_remind = lang('successful_ordering_delivery');
        } elseif (empty($pay_amount_offline)) {
            $order_remind = lang('timely_payment');
        } else {
            $order_remind = lang('payment_soon_possible');
        }
        $result['order_remind'] = $order_remind;
        $result['pay_amount_online'] = ds_price_format($pay_amount_online);
        //        $this->assign('pd_amount', ds_price_format($pd_amount));
        //显示支付接口列表
        if ($pay_amount_online > 0) {
            $payment_model = new Payment();
            $condition = array();
            $condition['payment_platform'] = 'pc';
            $payment_list = $payment_model->getPaymentOpenList($condition);
            if (empty($payment_list)) {
                return json_fail_return(lang('appropriate_payment_method'));
            }
            foreach ($payment_list as $key => $payment) {
                if (in_array($payment['payment_code'], array('predeposit', 'offline'))) {
                    unset($payment_list[$key]);
                }
            }
            $result['payment_list'] = $payment_list;
        }

        json_success_return('success', $result);
    }

    /**
     * @title 商城支付
     * @description 34000
     * @param string payment_code 支付方式alipay
     * @param string pay_sn 支付流水号
     * @return {"code":200,"msg":"succeess"}
     * @author fuzz
     * @url /Order/pay
     * @method POST
     *
     * @code 200 成功
     * @code 201 失败
     *
     */
    public function pay()
    {
        $payment_code = input('param.payment_code');
        $pay_sn = input('param.pay_sn');
        if(empty($pay_sn)){
            return json_fail_return('支付单号为空');
        }
        $orderModel = new \app\common\logic\Order();
        $apiPayModel = new ApiPayment();

        $orderData = $apiPayModel->getRealOrderInfo($pay_sn);
        if (intval($orderData['data']['api_paystate'])) {
            //订单已支付
            return json_fail_return('订单已支付');
        }
        $order_list = $orderData['data']['order_list'];
        $post['payment_code'] = $payment_code;
        $post['trade_no'] = '虚拟订单';
        $result = $orderModel->changeOrderReceivePay($order_list, 'system', '系统', $post);
        if ($result['code']) {
            json_success_return('success');
        } else {
            json_fail_return('fail');
        }
    }

    /**
     * @title 项目定制支付
     * @description
     * @param string payment_code 支付方式alipay
     * @param string pay_sn 支付流水号
     * @return {"code":200,"msg":"succeess"}
     * @author fuzz
     * @url /Order/pay
     * @method POST
     *
     * @code 200 成功
     * @code 201 失败
     *
     */
    public function project_pay()
    {
        $payment_code = input('param.payment_code');
        $pay_sn = input('param.pay_sn');

        #改支付状态
        db('orderpay')->where(['pay_sn' => $pay_sn])->update(['api_paystate' => 1]);

        #改订单状态
        db('orderproject')->where(['pay_sn' => $pay_sn])->update(['order_state' => 20, 'payment_time' => time()]);

        #改支付状态
        $order_info = db('order')->where(['pay_sn' => $pay_sn])->find();
        db('order')->where(['pay_sn' => $pay_sn])->update(['payment_time' => time()]);
        db('app_order')->where(['order_ids' => $order_info['order_id']])->update(['order_status' => 1]);


        #更新订单缓存表，用于统计数据
        $order_info = db('orderproject')->where(['pay_sn' => $pay_sn])->find();
        db('statorder')->where(['order_id' => $order_info['order_id']])->update(['order_state' => 20]);

        json_success_return('success');
    }

    /**
     * @title 服务订单支付
     * @description
     * @param string payment_code 支付方式alipay
     * @param string pay_sn 支付流水号
     * @return {"code":200,"msg":"succeess"}
     * @author fuzz
     * @url /Order/pay
     * @method POST
     *
     * @code 200 成功
     * @code 201 失败
     *
     */
    public function service_pay()
    {
        $payment_code = input('param.payment_code');
        $pay_sn = input('param.pay_sn');

        #改支付状态
        db('orderpay')->where(['pay_sn' => $pay_sn])->update(['api_paystate' => 1]);

        #改订单状态
        db('s_order')->where(['pay_sn' => $pay_sn])->update(['order_state' => 20, 'payment_time' => time()]);

        #改支付状态
        $order_info = db('order')->where(['pay_sn' => $pay_sn])->find();
        db('order')->where(['pay_sn' => $pay_sn])->update(['payment_time' => time()]);
        db('app_order')->where(['order_ids' => $order_info['order_id']])->update(['order_status' => 1]);


        #更新订单缓存表，用于统计数据
        $order_info = db('orderproject')->where(['pay_sn' => $pay_sn])->find();
        db('statorder')->where(['order_id' => $order_info['order_id']])->update(['order_state' => 20]);

        json_success_return('success');
    }


    /**
     * type express_code
     * postid shipping_code
     */
    public function express()
    {

        $url = 'http://www.kuaidi100.com/query?type=' . input('get.express_code') . '&postid=' . input('get.shipping_code') . '&id=1&valicode=&temp=' . random(4) . '&sessionid=&tmp=' . random(4);
        $content = do_http_request($url);
        $content = json_decode($content, true);

        if ($content['status'] != 200)
            exit(json_encode(false));
        $content['data'] = array_reverse($content['data']);
        $output = array();
        if (is_array($content['data'])) {
            foreach ($content['data'] as $k => $v) {
                if ($v['time'] == '')
                    continue;
                $output[] = $v['time'] . '&nbsp;&nbsp;' . $v['context'];
            }
        }
        if (empty($output))
            return json_fail_return();

        return json_success_return($output);
    }

    /**
     * @title 收银台
     * @description
     * @param string payment_code 支付方式alipay
     * @param string pay_sn 支付流水号
     * @return {"code":200,"msg":"succeess"}
     * @author fuzz
     * @url /Order/pay
     * @method POST
     *
     * @code 200 成功
     * @code 201 失败
     *
     */
    public function cashier()
    {
        $data = db('payment')->where(['payment_state' => 1])->select();
        return json_success_return($data);
    }

    /**
     * @title 获取七牛云token
     * @description
     * @param string payment_code 支付方式alipay
     * @param string pay_sn 支付流水号
     * @return {"code":200,"msg":"succeess"}
     * @author fuzz
     * @url /Order/pay
     * @method POST
     *
     * @code 200 成功
     * @code 201 失败
     *
     */
    public function get_qiniu_token()
    {
        $qiniu_accesskey = db('config')->where('code', 'qiniu_accesskey')->find();
        $qiniu_secretKey = db('config')->where('code', 'qiniu_secretKey')->find();
        $qiniu_bucket = db('config')->where('code', 'qiniu_bucket')->find();
        $qiniu_http = db('config')->where('code', 'qiniu_http')->find();

        require_once APP_PATH . '/../vendor/php-qiniu/qiniu/php-sdk/autoload.php';
        // 需要填写你的 Access Key 和 Secret Key
        $data['accessKey'] = $qiniu_accesskey['value'];

        $data['secretKey'] = $qiniu_secretKey['value'];
        // 构建鉴权对象
        $auth = new Auth($data['accessKey'], $data['secretKey']);
        // 要上传的空间
        $data['bucket'] = $qiniu_bucket['value'];
        $data['domain'] = $qiniu_http['value'];

        $data['token'] = $auth->uploadToken($data['bucket']);

        return json_success_return($data);
    }

    /**
     * @title 实时查询物流单号
     * @description
     * @param string payment_code 支付方式alipay
     * @param string pay_sn 支付流水号
     * @return {"code":200,"msg":"succeess"}
     * @author fuzz
     * @url /Order/pay
     * @method POST
     *
     * @code 200 成功
     * @code 201 失败
     *
     */
    public function get_query_logistics()
    {
        //订单id
        $order_id = input('param.order_id');

        if (empty($order_id)) {
            return json_fail_return('参数错误');
        }

        //判断当前订单的状态
        $order_info = db('order')->where(['order_id' => $order_id])->find();

        //物流单号 快递编码
        $logistics_num = $order_info['shipping_code'];
        $logistics_com = $order_info['shipping_com'];

        //通过物流编码获取物流公司名称
        $express_info = db('express')->where(['express_code' => $logistics_com])->find();

        $logistics_data = [
            'logistics_name' => $express_info['express_name'],
            'logistics_num'  => $order_info['shipping_code']
        ];

        if (empty($logistics_num) || empty($logistics_com)) {
            return json_fail_return('参数错误');
        }

        //30已发货
        if ($order_info['order_state'] < 30) {
            return json_fail_return('暂不可查询');
        }
        //返回两层数组
        $logistics_info = $logistics_data;
        $logistics_info['data'] = get_query_logistics($logistics_com, $logistics_num);

        //判断能不能查到
        if ($logistics_info['data'] == 1) {
            $logistics_info['data'] = [];
            return json_success_return($logistics_info);
        } else {
            return json_success_return($logistics_info);
        }
    }

    /**
     * @title 退货时  获取供应商的发货地址  以便于退货查看
     * @description
     * @param string
     * @param string
     * @param string
     * @param string
     * @return {"code":200,"msg":"succeess"}
     * @author zjw
     * @url /Order/get_shipping_daddress
     * @method POST
     *
     * @code 200 成功
     * @code 201 失败
     *
     */
    public function get_shipping_daddress()
    {
        //商品id
        $ordergoods_id = input('param.rec_id');

        if (empty($ordergoods_id)) {
            return json_fail_return('参数错误');
        }

        //获取到订单商品表的信息  (用于获取到订单id)
        $ordergoods_info = db('ordergoods')->where(['rec_id' => $ordergoods_id, 'buyer_id' => $this->user_id])->find();

        //获取订单扩展表的信息   （获取店铺id 和发货商的发货地址id）
        $ordercommon_info = db('ordercommon')->where(['order_id' => $ordergoods_info['order_id']])->find();


        $daddress_info = db('daddress')->where(['store_id' => $ordercommon_info['store_id'], 'daddress_id' => $ordercommon_info['daddress_id']])->find();

        return json_success_return($daddress_info);
    }

    /**
     * @title 收货完成   ：有安装费（申请安装服务）  有质保期（申请售后）

     * @param string
     * @param string

     * @param string
     * @param string

     * @return {"code":200,"msg":"succeess"}
     * @author zjw
     * @url /Order/get_customer_service
     * @method POST
     *
     * @code 200 成功
     * @code 201 失败
     *
     */
    public function get_customer_service()
    {
        //商品id
        $goods_id = input('param.goods_id');

        if (empty($goods_id)) {
            return json_fail_return('参数错误');
        }


        //获取到商品表的信息  
        $goods_info = db('goods')->where(['goods_id' => $goods_id])->find();

        if (empty($goods_info)) {
            return json_fail_return('商品信息错误');
        }

        $result = [];
        //判断是否有安装费
        if ($goods_info['install_money'] > 0) {
            $result['msg'] = 1;
        }
        //判断是否有质保期
        if ($goods_info['warranty_period'] > 0) {
            $result['msg'] = 2;
        }
        //判断是否有安装费  和 质保期
        if ($goods_info['install_money'] > 0 && $goods_info['warranty_period'] > 0) {
            $result['msg'] = 3;
        }
        return json_success_return($result);
    }



    // 1、首先接入微信进件 获取companyNo（入驻）
    public function getCompanyNo()
    {
        // 1、首先接入微信进件 获取companyNo
        $huichao = new Huichao();
        $companyNo = $huichao->wechatInCase('WXZF_ONLINE');

        $xml =  base64_decode($companyNo);

        $obj = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        var_dump($obj);
        exit;
    }


    /**
     * @title  同步 聚合支付(微信/支付宝直接唤起支付界面)
     * @description
     * @param string payment_code 支付方式alipay
     * @param string
     * @return {"code":200,"msg":"succeess"}
     * @author zjw
     * @url /Order/get_pay_info
     * @method POST
     *
     * @code 200 成功
     * @code 201 失败
     *
     */
    public function get_pay_info()
    {
        //2、获取小程序的oppenid
        $code = input('param.code');
        $appid  = 'wx33ce2dbde6f86814'; //小程序appid
        $secret = 'cb855728112ce02942e164bd053c6da0';
        $URL = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code";
        $apiData = file_get_contents($URL);
        $wxInfo = json_decode($apiData, true);

     
        // 3、 调起聚合支付
        $data['merchantOrderNo'] = input('param.orderno'); //订单编号
        $data['payType'] = 'WxJsapi_OnLine'; //支付类型
        $data['amount'] = 0.01; //支付金额
        $data['adviceURL'] = 'https://three.douyinhot.com/index.php/api/home/get_asynchronous_res'; //微信异步通知
        $data['shareProfitUrl'] = 'https://three.douyinhot.com/index.php/api/home/get_pernetwork_res'; //微信异步通知
        $data['scanpayMerchantCode'] = 'sweep-3e6a170dbc594818811b563d1204722a'; //渠道商户编码(扫码商户进件返回的参数companyNo)
        $data['products'] = '三三网'; //商品描述
        $data['remark'] = '小邹测试';
        $data['credit'] = 'false';
        $data['shareProfitData']['shareProfitList'] = [
            'amount' => 0.01,
            'payeeMerNo' => '50326_10001',
            'remark' =>'测试支付'
        ];
        $data['shareProfitData']['shareProfitType'] = 11;
        $data['userId'] = $wxInfo['openid'];
        $data['subAppid'] = $appid; //小程序appid

        $url = 'https://fzapi.yemadai.com/sp/aggregatePay';
        $huichao = new Huichao();
        // var_dump($data);exit;
        $result = $huichao->getPayInfo($url, $data);

        // 4、获取返回集的数组  将支付需要的5个参数转为数组返回
        $wx_payment = json_decode($result, true);
        
        if($wx_payment['code'] == 'SUCCESS'){
            $wx_payment_info = json_decode($wx_payment['qRCode'], true);
            return json_success_return($wx_payment_info);
        }else{
            return json_fail_return($wx_payment['message']);
        }
    }

    /**
     * @title  项目定制支付
     * @description
     * @param string payment_code 支付方式alipay
     * @param string
     * @return {"code":200,"msg":"succeess"}
     * @author zjw
     * @url /Order/get_pay_info
     * @method POST
     *
     * @code 200 成功
     * @code 201 失败
     *
     */
    public function get_project_payinfo()
    {
        //2、获取小程序的oppenid
        $code = input('param.code');
        $appid  = 'wx33ce2dbde6f86814'; //小程序appid
        $secret = 'cb855728112ce02942e164bd053c6da0';
        $URL = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code";
        $apiData = file_get_contents($URL);
        $wxInfo = json_decode($apiData, true);


        // 3、 调起聚合支付
        $data['merchantOrderNo'] = input('param.orderno'); //订单编号
        $data['payType'] = 'WxJsapi_OnLine'; //支付类型
        $data['amount'] = 0.01; //支付金额
        $data['adviceURL'] = 'https://three.douyinhot.com/index.php/api/home/get_project_asynchronous_res'; //微信异步通知
        $data['shareProfitUrl'] = 'https://three.douyinhot.com/index.php/api/home/get_pernetwork_res'; //微信异步通知
        $data['scanpayMerchantCode'] = 'sweep-3e6a170dbc594818811b563d1204722a'; //渠道商户编码(扫码商户进件返回的参数companyNo)
        $data['products'] = '三三网'; //商品描述
        $data['remark'] = '小邹测试';
        $data['credit'] = 'false';
        $data['shareProfitData']['shareProfitList'] = [
            'amount' => 0.01,
            'payeeMerNo' => '50326_10001',
            'remark' =>'测试支付'
        ];
        $data['shareProfitData']['shareProfitType'] = 11;
        $data['userId'] = $wxInfo['openid'];
        $data['subAppid'] = $appid; //小程序appid

        $url = 'https://fzapi.yemadai.com/sp/aggregatePay';
        $huichao = new Huichao();
        // var_dump($data);exit;
        $result = $huichao->getPayInfo($url, $data);

        // 4、获取返回集的数组  将支付需要的5个参数转为数组返回
        $wx_payment = json_decode($result, true);

        if($wx_payment['code'] == 'SUCCESS'){
            $wx_payment_info = json_decode($wx_payment['qRCode'], true);
            return json_success_return($wx_payment_info);
        }else{
            return json_fail_return($wx_payment['message']);
        }
    }

    //子商户入网 （同步）
    public function pernetwork() {
		$arr = [
			'subMerType' => 3,//个人
			'subMerName' => '山陆久', //姓名
			'merShortName' => '',	//商户简称
			// 'contacts' => '',	//联系人
			// 'merLicense' => '',	//营业执照  3 可空
			// 'licenseValidity' => '',	//营业执照期限
			'legalName' => '邹建伟',	//联系人
			'legalMobile' => '18832300442',	//联系人
			'legalIdNo' => '130724199709092811',	//联系人
			'legalValidity' => '20280123',	//证件有效期
			'legalValidityFlag' => 2,	//
			'legalBankCard' => '6217855000019807106',	//联系人
			'legalBankName' => '中国银行',	//联系人
			'regCapital' => '0',	//联系人
			'minSettleAmout' => '0',	//联系人
			'riskDeposit' => '0',	
			'companyAddress' => '河北省保定市竞秀区',	
		];

		$huichao = new Huichao();
	
		$res = $huichao->spNetwork($arr);
		echo '<pre>';
		var_dump(json_decode($res, true));exit;
		echo json_encode($res);exit;
	}

    /**
     * @title   确认是否入驻成功了。
     * @description
     * @param string payment_code 支付方式alipay
     * @param string
     * @return {"code":200,"msg":"succeess"}
     * @author zjw
     * @url /Order/get_settled_info
     * @method POST
     *
     * @code 200 成功
     * @code 201 失败
     *
     */
    public function get_settled_info()
    {
        // 1、首先接入微信进件 获取companyNo
        $huichao = new Huichao();

        $result = $huichao->getSettledInfo('WXZF_ONLINE', 'sweep-585cdf05f8124e26a457365421868a38');

        echo base64_decode($result);
        exit;
        return json_success_return();
    }


    //项目定制订单流程和具体问题
    //1.创建新订单(不经过购物车)
    //2.需要查项目定制商品具体的数量存储在项目订单详情表。
    //3.计算具体金额（项目费+咨询费+服务费+实施费-积分抵扣-优惠券）
    //4.项目定制销量增加  商品库存数量减少
    //5.订单状态（待支付（未付款），进行中（已发货，已收货），待评价（已完成），已完成（已取消，已评价）,已退款）
    //
    //2/13

    /**
     * @title 项目定制预订单
     * @description
     * @param string ifcart 是否来自购物车1是0否
     * @param string cart_id 商品信息格式id|number
     * @return {"code":200,"msg":"succeess"}
     * @author fuzz
     * @url /Order/prepare
     * @method POST
     *
     * @code 200 成功
     * @code 201 失败
     *
     */
    public function prepare2()
    {
        if (empty(input('post.'))) {
            return json_fail_return(lang('wrong_argument'));
        }
        if (empty(input('post.project_id'))) {
            return json_fail_return('参数错误');
        }

        //获取项目定制预订单的全部信息
        $buy_logic = new Buy();
        $result = $buy_logic->buyStep1_project(input('post.project_id'), $this->user_id);
        if ($result['code'] != 'SUCCESS') {
            return json_fail_return($result['msg']);
        } else {
            json_success_return('success', $result);
        }
    }


    /**
     * @title 项目定制订单创建
     * @description
     * @param array cart_id 是否来自购物车1是0否
     * @param string pay_message 备注店铺id为键message为值
     * @param string order_from 固定值2
     * @param string ifcart 是否来自购物车
     * @param string pay_name 固定值online
     * @param string pay_name 是否保存增值税发票判断标志
     * @param string address_id 地址id
     * @param string buy_city_id 收货城市id
     * @param string allow_offpay 是否支持货到付款
     * @param string allow_offpay_batch 地区满减信息
     * @param string offpay_hash 地区满减信息
     * @param string offpay_hash_batch 地区满减信息
     * @param string prodect_id 项目id
     * @return {"code":200,"msg":"succeess"}
     * @author fuzz
     * @url /Order/create
     * @method POST
     *
     * @code 200 成功
     * @code 201 失败
     *
     */
    public function create2(Seller $seller)
    {

        $buy_logic = new Buy();
        $result = $buy_logic->buyStep4(input('post.'), $this->user_id, $this->user_info['member_name'], $this->user_info['member_email']);
        //p($result);die;
        if (!$result['code']) {
            return json_fail_return($result['msg']);
        }

        json_success_return('创建订单成功', $result['data']);
    }




    //项目定制订单列表
    public function project_list()
    {
        if (empty(input('post.'))) {
            return json_fail_return(lang('wrong_argument'));
        }

        $order_state = input('post.order_state');
        $page = intval(input('page')) ? intval(input('page')) : 1;
        $pagesize = intval(input('pagesize')) ? intval(input('pagesize')) : 15;
        $offset = ($page - 1) * $pagesize;

        switch ($order_state) {
            case 1: #待支付
                $where['order_state'] = 10;
                break;
            case 2: #进行中
                $where['order_state'] = array('in', '20,30,60');
                break;
            case 3: #待评价
                $where['order_state'] = 40;
                $where['evaluation_state'] = array('neq', 1);
                break;
            case 4: #已完成
                $where['order_state'] = array('in', '0,40,50,55');
                $where['evaluation_state'] = 1;
                break;
            default:
                break;
        }
        $where['buyer_id'] = $this->user_id;

        $tblname = 'orderproject';
        $result = db($tblname)->field('order_id,evaluation_state,order_state,project_name,project_image,project_price,add_time,pay_sn,order_amount')->order('add_time desc')->where($where)->limit($offset, $pagesize)->select();

        json_success_return($result);
    }

    //项目定制订单详情
    public function order_project()
    {
        $order_id = input('post.order_id');
        if (empty($order_id)) {
            return json_fail_return('参数错误');
        }

        $where['order_id'] = $order_id;
        $where['buyer_id'] = $this->user_id;

        //获取订单详情
        $order_info = db('orderproject')->alias('op')
            ->join('goodsproject gp', 'gp.project_id=op.project_id')
            ->join('goodsproject_class gpc', 'gpc.id=gp.project_class')
            ->field('op.*,gp.*,gp.status as project_status,gpc.*')
            ->where($where)
            ->find();

        #生成商品单之后           
        if ($order_info['goodsbill'] == 1) {
            $order_info = db('orderproject')->alias('op')
                ->join('app_order ao', 'ao.app_order_project_id=op.order_id')
                ->join('goodsproject gp', 'gp.project_id=op.project_id')
                ->join('goodsproject_class gpc', 'gpc.id=gp.project_class')
                ->field('op.*,gp.*,ao.*,gp.status as project_status,gpc.*')
                ->where($where)
                ->find();
        }

        #判断是否收藏
        $project_collection = db('favorites')->where(['member_id' => $where['buyer_id'], 'fav_type' => 2, 'fav_id' => $order_info['project_id']])->select();

        $order_info['is_collection'] = 0; #未收藏   
        if (!empty($project_collection)) {
            $order_info['is_collection'] = 1; #已收藏   
        }

        $config = db('config')->where('code', 'qiniu_http')->find();
        $order_info['project_images'] = $config['value'] . '/' . $order_info['project_images'];

        //获取项目定制里面包含的商品
        $order_info['goods_list'] = db('orderproject_goods')->where(['order_id' => $order_id])->select();

        $total_nums = 0; #总商品件数
        foreach ($order_info['goods_list'] as $key => $value) {
            $total_nums += $value['goods_num'];
        }
        $order_info['total_nums'] = $total_nums;

        json_success_return($order_info);
    }

    //项目定制取消订单
    public function order_project_cancel()
    {
        $order_id = input('post.order_id'); #项目定制id
        if (empty($order_id)) {
            return json_fail_return('参数错误');
        }

        $where['order_id'] = $order_id;
        $where['buyer_id'] = $this->user_id;

        //获取订单详情
        $order_info = db('orderproject')->alias('op')
            ->join('goodsproject gp', 'gp.project_id=op.project_id')
            ->where($where)
            ->find();

        if (empty($order_info)) {
            return json_fail_return('暂无订单信息');
        }

        if ($order_info['order_state'] == 0) {
            return json_fail_return('无需重复操作');
        }

        #取消订单更改 商城订单和项目定制订单状态
        db('orderproject')->where(['order_id' => $order_id])->update(['order_state' => 0, 'evaluation_state' => 1]);
        db('order')->where(['order_id' => $order_info['order_mall_id']])->update(['order_state' => 0, 'evaluation_state' => 1]);

        #减少销量
        $project_info = db('goodsproject')->where(['project_id' => $order_info['project_id']])->find();

        $sale_num = $project_info['sale_num'] - 1;
        db('goodsproject')->where(['project_id' => $order_info['project_id']])->update(['sale_num' => $sale_num]);
        json_success_return();
    }

    //项目定制 确认完成
    public function order_project_over()
    {
        $order_id = input('post.order_id'); #项目定制id
        if (empty($order_id)) {
            return json_fail_return('参数错误');
        }

        $where['order_id'] = $order_id;
        $where['buyer_id'] = $this->user_id;

        //获取订单详情
        $order_info = db('orderproject')->alias('op')
            ->join('goodsproject gp', 'gp.project_id=op.project_id')
            ->where($where)
            ->find();

        if (empty($order_info)) {
            return json_fail_return('暂无订单信息');
        }

        #确认完成 更改项目定制订单状态
        db('orderproject')->where(['order_id' => $order_id])->update(['order_state' => 40]);

        #根据订单编号修改统计的状态
        db('statorder')->where(['order_sn' => $order_info['order_sn']])->update(['order_state' => 50]);

        json_success_return();
    }

    //商城售后服务生成服务单
    public function order_customer_service()
    {
        $rec_id  = input('post.rec_id'); #订单商品id
        $order_type  = input('post.order_type'); #订单类型 1--安装（安装） 2--售后（维修）

        $order_goods_info = db('ordergoods')->alias('og')
            ->join('goods g', 'g.goods_id = og.goods_id')
            ->where(['rec_id' => $rec_id])
            ->find();
        $spec_type = explode(",", $order_goods_info['spec_values']);

        $goods_data = [
            'goods_id' => $order_goods_info['goods_id'],
            'goods_name' => $order_goods_info['goods_name'],
            'gc_id' => $order_goods_info['gc_id'],
            'gc_id_1' => $order_goods_info['gc_id_1'],
            'gc_id_2' => $order_goods_info['gc_id_2'],
            'gc_id_3' => $order_goods_info['gc_id_3'],
            'brand_id' => $order_goods_info['brand_id'],
            'spec_type' => $spec_type[0],
            'spec_model' =>  $spec_type[1],
        ];
        json_success_return($goods_data);
    }

    //为您推荐
    public function order_recommend()
    {
        $goods_id  = input('post.goods_id'); #订单商品id

        $goods_info = db('goods')
            ->where(['goods_id' => $goods_id])
            ->find();

        //获取当前商品的所有不同规格商品
        $all_goods_info = db('goods')->where(['goods_commonid' => $goods_info['goods_commonid']])->select();

        $goods_array = [];
        foreach ($all_goods_info as $k => $v) {
            $goods_array[] = $v['goods_id'];
        }

        $page = intval(input('page')) ? intval(input('page')) : 1;
        $pagesize = intval(input('pagesize')) ? intval(input('pagesize')) : 15;
        $offset = ($page - 1) * $pagesize;
        $parms = [
            'gc.store_id' =>  $goods_info['store_id'],
            'g.goods_id' => ['not in', $goods_array],
            'gc.goods_lock' => 0, #未删除   
            'gc.is_two_goods' => 0,#不是二手商品  
            'gc.goods_status' =>1
        ];
        $field = 'g.goods_id,gc.goods_commonid,gc.goods_image,g.goods_price,gc.goods_name';
        $goods_list = db('goodscommon')->alias('gc')
            ->join('goods g', 'g.goods_commonid = gc.goods_commonid')
            ->field($field)
            ->limit($offset, $pagesize)
            ->where($parms)
            ->select();

        $config = db('config')->where('code', 'qiniu_http')->find();

        $new = []; #返回的数据
        $new_goods_list = [];
        foreach ($goods_list as $k => $v) {
            $v['goods_image'] = $config['value'] . '/' . $v['goods_image'];
            if (!in_array($v['goods_commonid'], $new_goods_list)) {
                $new[] = $v;
                $new_goods_list[] = $v['goods_commonid'];
            }
        }
        json_success_return($new);
    }
     //获取服务端极光imid
    public function getKIm(){
        $order_id = intval(input('param.order_id'));
        $order_info = db('s_order')->alias('so')
                    ->join('fuwu_personal fp','fp.id = so.assign_mechanic_id')
                    ->field('so.order_id,fp.id,so.member_id,fp.phone')
                    ->where(['order_id'=>$order_id])
                    ->find();
        json_success_return(['cliend'=>'fuwu'.$order_info['phone']]);
    }
}
